package com.shi.vueblog.controller;

import com.shi.vueblog.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("file")
public class FileController {

    @Value("${shi.upload}")
    private String filePath;

    /**
     * 文件上传
     * @param image image
     * @return Map<String, Object>
     */
   @PostMapping("/uploadImg")
    public Result uploadFile(MultipartFile image) throws IOException {
        String fileName=image.getOriginalFilename();//文件全名称
        String fileSuffix=fileName.substring(fileName.lastIndexOf("."),fileName.length());//文件后缀名
        String fileNewName=System.currentTimeMillis()+fileSuffix;
        String path=filePath+File.separator+fileNewName;
        File newFile=new File(path);
        File derfile=new File(filePath);
        if(!derfile.exists()){
            derfile.mkdirs();
        }
        image.transferTo(newFile);
        String pathname="/file/"+fileNewName;// 必须是完整的路径
       Map<String,String>map=new HashMap<String, String>();
       map.put("url",pathname);
       return Result.succ("成功",map);
    }
}
